#!/bin/bash
# This script creates a kubernetes persistent volume with no storageclass
# It serves for the kubeflow component —— tf-hub
# since the tf-hub create a new notebook with mount to a pv with no storageclass

set -xe

uuid=`uuidgen`
uuid=${uuid:0:8}

USER_NAMESPACE=${USER_NAMESPACE:-"default"}
if [ -z "${1}" ]; then
	echo "user namespace nil, use default namespace"
else
	USER_NAMESPACE=$1
fi

TF_NOTEBOOK_YAML_TMP=/tmp/tf-notebook-${uuid}.yaml
TF_TENSORBOARD_YAML_TMP=/tmp/tf-tensorboard-${uuid}.yaml

cp ../yaml/notebook.yaml ${TF_NOTEBOOK_YAML_TMP}

cp ../yaml/tf_tensorboard.yaml ${TF_TENSORBOARD_YAML_TMP}

sed -i "s/uuidgen/${uuid}/g" ${TF_NOTEBOOK_YAML_TMP}
sed -i "s/uuidgen/${uuid}/g" ${TF_TENSORBOARD_YAML_TMP}

# cat ${TF_NOTEBOOK_YAML_TMP}
# cat ${TF_TENSORBOARD_YAML_TMP}

kubectl create -f ${TF_TENSORBOARD_YAML_TMP} -n ${USER_NAMESPACE}
sleep 1
kubectl create -f ${TF_NOTEBOOK_YAML_TMP} -n ${USER_NAMESPACE}

# see if the pv and pvc were created properly
kubectl get pv
kubectl get pvc -n ${USER_NAMESPACE}

while [ ! -d "/cephfs/jupyterhubpv/${uuid}" ]; do
	sleep 1
done

mkdir -p /cephfs/jupyterhubpv/${uuid}/work
chmod -R 777 /cephfs/jupyterhubpv/${uuid}

set +xe

TENSORBOARD_PORT=`kubectl get svc -n ${USER_NAMESPACE}| grep tensorboard-manual-${uuid} | awk '{print $5}'`
TENSORBOARD_PORT=${TENSORBOARD_PORT##*:}
TENSORBOARD_PORT=${TENSORBOARD_PORT%/*}

JUPYTER_HUB_PORT=`kubectl get svc -n ${USER_NAMESPACE} | grep tf-hub-lb | awk '{print $5}'`
JUPYTER_HUB_PORT=${JUPYTER_HUB_PORT##*:}
JUPYTER_HUB_PORT=${JUPYTER_HUB_PORT%/*}

exit 0